import indexObj from '../../unit/index.js';
import event from '../../unit/event';
import states from '../states';
import musicobj from '../../unit/music';
import Block from '../../unit/block.js';
let {
	want
} = indexObj;
let {
	music
} = musicobj;

const down = (store) => {
	store.commit("down", true);
	if (store.state.cur !== null) {
		event.down({
			key: 'down',
			begin: 40,
			interval: 40,
			callback: (stopDownTrigger) => {
				const state = store.state;
				if (state.lock) {
					return;
				}
				if (music.move) {
					music.move();
				}
				const cur = state.cur;
				if (cur === null) {
					return;
				}
				if (state.pause) {
					states.pause(false);
					return;
				}
				const next = cur.fall();
				if (want(next, state.matrix)) {
					// store.dispatch(actions.moveBlock(next));
					store.commit("moveBlock", next.reset === true ? null : new Block(next));
					states.auto();
				} else {
					let matrix = state.matrix;
					const shape = cur.shape;
					const xy = cur.xy;
					shape.forEach((m, k1) => (
						m.forEach((n, k2) => {
							if (n && xy[0] + k1 >= 0) { // 竖坐标可以为负
								let line = matrix[xy[0] + k1];
								line[xy[1] + k2] = 1;
								matrix[xy[0] + k1] = line;
							}
						})));
					states.nextAround(matrix, stopDownTrigger);
				}
			},
		});
	} else {
		event.down({
			key: 'down',
			begin: 200,
			interval: 100,
			callback: () => {
				const state = store.state;
				if (state.lock) {
					return;
				}
				if (state.cur) {
					return;
				}
				if (music.move) {
					music.move();
				}
				let startLines = state.startLines;
				startLines = startLines - 1 < 0 ? 10 : startLines - 1;
				store.commit("startLines", startLines);
			},
		});
	}
};

const up = (store) => {
	store.commit("down", false);
	event.up({
		key: 'down',
	});
};




export default {
	down,
	up,
};